package com.javalab.recorder.audio;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

import org.apache.log4j.Logger;

import com.javalab.recorder.state.StoppedState;
import com.javalab.recorder.ui.MainFrame;

public class AudioPlaybackThread implements Runnable {

	private byte[] audioData;

	private MainFrame mainFrame;

	private boolean playing;

	private static Logger logger = Logger.getLogger(AudioPlaybackThread.class);

	@Override
	public void run() {
		SourceDataLine sourceDataLine = null;
		try {
			sourceDataLine = AudioDevice.getInstance().getDefaultSourceDataLine();
			sourceDataLine.open(AudioDevice.getInstance().getDefaultAudioFormat());
			sourceDataLine.start();
			ByteArrayInputStream bas = new ByteArrayInputStream(audioData);
			int count = -1;
			byte[] buffer = new byte[sourceDataLine.getBufferSize() / 5];
			while ((count = bas.read(buffer)) >= 0 && playing) {
//				sourceDataLine.write(audioData, 0, audioData.length);
				sourceDataLine.write(buffer, 0, count);
			}
			sourceDataLine.drain();
			mainFrame.setRecorderState(StoppedState.getInstance());
		} catch (LineUnavailableException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			sourceDataLine.stop();
			sourceDataLine.close();
		}
	}

	public void startPlaying() {
		Thread thread = new Thread(this);
		playing = true;
		thread.start();
	}

	public void stopPlaying() {
		playing = false;
	}

	public byte[] getAudioData() {
		return audioData;
	}

	public void setAudioData(byte[] audioData) {
		this.audioData = audioData;
	}

	public MainFrame getMainFrame() {
		return mainFrame;
	}

	public void setMainFrame(MainFrame mainFrame) {
		this.mainFrame = mainFrame;
	}

}
